package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.DictDao;
import com.atguigu.entity.Dict;
import com.atguigu.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = DictService.class)
@Transactional
public class DictServiceImpl extends BaseServiceImpl<Dict> implements DictService {

   @Autowired
   private DictDao dictDao;

   @Override
   public List<Map<String,Object>> findZnodes(Long id) {
      // 返回数据[{ id:2, isParent:true, name:"随意勾选 2"}]
      //1.根据id获取子节点数据
      List<Dict> dictList = dictDao.findListByParentId(id);

      //2.通过循环转换为指定json格式（其中要判断该节点是否是父节点）
      List<Map<String,Object>> zNodes = new ArrayList<>();
      for (Dict dict:dictList){
         Integer count = dictDao.countIsParent(dict.getId());
         Map<String,Object> map = new HashMap<>();
         map.put("id",dict.getId());
         map.put("isParent",count > 0 ? true : false);
         map.put("name",dict.getName());
         zNodes.add(map);
      }
      return zNodes;
   }

   @Override
   public List<Dict> findListByDictCode(String dictcode) {
      Dict dict = dictDao.getByDictCode(dictcode);
      if (dict == null) {
         return null;
      }
      List<Dict> dictList = this.dictDao.findListByParentId(dict.getId());
      return dictList;
   }

   @Override
   public List<Dict> findListByParentId(Long parentId) {
      List<Dict> dictList = this.dictDao.findListByParentId(parentId);
      return dictList;
   }

   @Override
   public String getNameById(Long dictId) {
      return dictDao.getNameById(dictId);
   }

   @Override
   public BaseDao<Dict> getEntityDao() {
      return dictDao;
   }
}